package com.life.xxx.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RefreshTokenService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String RT_KEY = "rt:user:%s"; // rt:user:123
    private static final long RT_TTL_SECONDS = 604800; // 7天

    /**
     * 保存 Refresh Token 到 Redis
     */
    public void save(String userId, String refreshToken) {
        String key = String.format(RT_KEY, userId);
        redisTemplate.opsForSet().add(key, refreshToken);
        redisTemplate.expire(key, RT_TTL_SECONDS, TimeUnit.SECONDS);
    }

    /**
     * 检查 Refresh Token 是否有效（存在）
     */
    public boolean isValid(String userId, String refreshToken) {
        String key = String.format(RT_KEY, userId);
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, refreshToken));
    }

    /**
     * 用户退出登录时，清除所有 Refresh Token
     */
    public void revokeAll(String userId) {
        String key = String.format(RT_KEY, userId);
        redisTemplate.delete(key);
    }
}